package com.yxh.controller;

import com.wordnik.swagger.annotations.ApiImplicitParam;
import com.wordnik.swagger.annotations.ApiImplicitParams;
import com.wordnik.swagger.annotations.ApiOperation;
import com.yxh.common.annotation.Authorization;
import com.yxh.dao.UserMapper;
import com.yxh.exception.UserException;
import com.yxh.pojo.TokenModel;
import com.yxh.pojo.User;
import com.yxh.pojo.vo.UserVO;
import com.yxh.service.TokenManager;
import com.yxh.util.CustomerContextHolder;
import com.yxh.util.MD5Util;
import com.yxh.util.Response;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.util.Date;

import static com.yxh.util.APIErrorCode.*;

/**
 * 获取和删除token的请求地址，在Restful设计中其实就对应着登录和退出登录的资源映射
 *
 * @author ScienJus
 * @date 2015/7/30.
 */
@RestController
@RequestMapping("/tokens/")
public class TokenController extends BaseController {

    private static final Logger logger = LoggerFactory.getLogger(TokenController.class);

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private TokenManager tokenManager;




    Response response;

    @PostMapping("login")
    @ApiOperation(value = "登录")
    public Response login(@RequestBody(required = false) User loginuser) {
        if (StringUtils.isEmpty(loginuser.getAccount())) {
            throw new UserException(USER_ACCOUNT);
        }
        if (StringUtils.isEmpty(loginuser.getPassword())) {
            throw new UserException(USER_PASSWORD);
        }
        //Assert.notNull(loginuser.getAccount(), "account can not be empty");
        //Assert.notNull(loginuser.getPassword(), "password can not be empty");
        String md5Password = MD5Util.MD5EncodeUtf8(loginuser.getPassword());
        User user = userMapper.selectByAccount(loginuser.getAccount());
        if (user == null ||  //未注册
                !user.getPassword().equals(md5Password)) {  //密码错误
            //提示用户名或密码错误
            throw new UserException(PASSWORD_ERROR);
        }

        //生成一个token，保存用户登录状态*/
        TokenModel model = tokenManager.createToken(user.getId());
        UserVO userVO = tokenManager.AssemblingData(user);
        if(loginuser.getModel()!=null)
            userVO.setToken(user.getId() + "_web" + model.getToken());//区分手机 pc 端登陆
            else
            userVO.setToken(user.getId() + "_" + model.getToken());
        //user = new User();
        user.setGmtModified(new Date());
        userMapper.updateByPrimaryKeySelective(user);

        //CustomerContextHolder.setContextType(CustomerContextHolder.SESSION_FACTORY_ORACLE);
        response = Response.returnResponse(SUCCESS);
        response.setData(userVO);
        return response;
    }

    @DeleteMapping("loginout")
    @Authorization
    @ApiOperation(value = "退出登录")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "authorization", value = "authorization", required = true, dataType = "string", paramType = "header"),
    })
    public Response logout(@RequestParam String userId) {
        tokenManager.deleteToken(userId);
        response = Response.returnResponse(SUCCESS);
        return response;
    }

}
